<template>
  <div>
    <el-card>
      <div slot="header" class="clearfix">
        <span class="header-class">基本资料</span>
      </div>
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="登录名称" style="margin-left: 10px;">
          <el-input class="input" v-model="form.username" disabled>{{form.username}}</el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input class="input" v-model="form.nickname" placeholder="请输入昵称">{{form.nickname}}</el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input class="input" v-model="form.email" placeholder="请输入邮箱">{{form.email}}</el-input>
        </el-form-item>
      </el-form>
      <el-button @click="updateInfo" type="primary" style="margin-left: 68px">提交修改</el-button>
      <el-button type="primary" plain @click="resetForm('form')">重置</el-button>
    </el-card>
  </div>
</template>

<script>
import { upInfo, getHeader } from '@/api/center'
export default {
  // 基本资料
  name: 'BasicInformation',
  data () {
    // 自定义邮箱规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^\w+@\w+(\.\w+)+$/
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback()
      }
      callback(new Error('邮箱格式不正确'))
    }
    return {
      form: {
        nickname: '',
        email: '',
        username: ''
      },
      rules: {
        nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 1, max: 10, message: '请输入1-10位的字符', trigger: 'blur' }],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }]
      }
    }
  },
  async created () {
    this.getInfo()
  },
  methods: {
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 更新用户基本资料
    async updateInfo () {
      try {
        // 校验表单
        const valid = await this.$refs.form.validate()
        if (valid) {
          const { id, nickname, email } = this.form
          await upInfo({ id, nickname, email })
          this.$message.success('修改成功')
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取 头像昵称 等
    async getInfo () {
      const res = await getHeader()
      this.form = {
        ...res.data
      }
      console.log(this.form)
    }

  }
}
</script>

<style scoped lang="less">
.header-class {
    line-height: 32px;
    font-size: 16px;
    font-weight: 600;
  }
 /deep/.input {
  width: 400px;
}
/deep/ .el-form-item__error{
  margin-left: 80px;
}
</style>
